class AuctionController {

    def allowedMethods = [delete: 'POST', save: 'POST', update: 'POST']

    def authenticateService

    static defaultAction = "list"

    def list = {

        def userDomain = authenticateService.userDomain()
        def loggedUser
        
        if (userDomain) {
            int loggedUserId = userDomain?.id
            loggedUser = User.get(loggedUserId)
        }

        def auctions

        params.max = params.max ?: 10
        params.sort = params.sort ?: "finish"
        params.order = params.order ?: "desc"

        if (loggedUser?.isAdmin()) {
            auctions = Auction.list(params)
        }
        else { //tylko aukcje, które już się rozpoczęły
                auctions = Auction.findAllByBeginLessThan(new Date(), params)
        }
        [auctions: auctions]
    }

    def show = {
        [auction: Auction.get(params.id)]
    }

    def create = {
        def auction = new Auction()

        auction.properties = params
        [auction: auction]
    }

    def save = {
        def auction = new Auction()
        auction.properties = params

        //ustawiamy, aby aukcja kończyła się o 23.59, a nie o 0.00
        Calendar calendar = Calendar.getInstance()
        calendar.setTime(auction.finish)

        if (calendar.get(calendar.HOUR) == 0
            && calendar.get(calendar.MINUTE) == 0
            && calendar.get(calendar.SECOND) == 0) {

            calendar.set(calendar.HOUR, 11)
            calendar.set(calendar.AM_PM, 1) //PM
            calendar.set(calendar.MINUTE, 59)
            calendar.set(calendar.SECOND, 59)
        }

        auction.finish = calendar.getTime()

        if (auction.save()) {
            redirect(action: "show", id: auction.id)
        }
        else {
            render(view: "create", model: [auction: auction])
        }
    }

    def delete = {
        def auction = Auction.get(params.id)

        if (auction) {
            auction.delete()
        }
        else {
            flash.message = "Auction not found with id ${params.id}"
        }

        redirect(action: list)
    }

    def edit = {
        def auction = Auction.get(params.id)

        if (!auction) {
            flash.message = "Auction not found with id ${params.id}"
            redirect(action: list)
            return
        }

        [auction: auction]
    }

    def update = {
        def auction = Auction.get(params.id)

        if (!auction) {
            flash.message = "Auction not found with id ${params.id}"
            redirect(action: list)
            return
        }

        auction.properties = params

        if (auction.save()) {
            redirect(action: show, id: params.id)
        }
        else {
            render(view: "edit", model: [auction: auction])
        }
    }
}
